<?php
namespace app\api\controller\V22;

use app\api\controller\Base;
use app\api\model\Configs;
use app\api\model\ModeProduct;
use app\api\model\Cart;
use think\helper\Str;

class ModeOrders extends Base
{
    // 不需要验证
    protected $excludeValidateCheck = [

    ];

    // 定义自动实例化模型
    protected $ModelPath = 'ModeOrders';

    public function create()
    {
        $isOpen = Configs::where('alias', 'IS_OPEN_WITHDRAWAL')->value('content');
        if($isOpen == 0){
            return showError('静态释放准备中');
        }
        $userId = $user_id = request()->UserModel->id;
        $orderData = request()->param();
//        if(empty($orderData['address'])){
//            return showError('请先选择收货地址');
//        }
        $cartId = $orderData['ids'];
        $cart = Cart::find($cartId);

        $productId = $cart['goods_id'];
        $productNum = $cart['goods_num'];

        $product = ModeProduct::find($productId);

        if((int)$product['type'] === 2 || (int)$product['type'] === 3) {
            return showError('库存不足');
        }

        if($product['type'] == 3){
            $count = \app\api\model\ModeOrders::where('user_id', $userId)
                ->where('status', 'payed')
                ->where('type', 3)
                ->count();
            if(($count + $productNum) > 5){
                return showError('每人最多购买5股');
            }
        }

        //计算金额
        //商品销售价格
        $productAmount = $product['price'];
        //商品总价格
        $totalAmount = $totalProductAmount = $productAmount * $productNum;
        //删购物车
        Cart::destroy($cartId);
//        dd($orderData);
        $insertData = $this->calcUserEarnings($userId, $productId, $productNum, $totalAmount);
//            [
//            // 订单号
//            'order_sn'              => 'MODE-A-' . date('YmdHis'),// . (microtime(true) * 10),
//            // 用户id
//            'user_id'               => $userId,
//            // 商品ID
//            'product_id'            => $productId,
//            // 商品数量
//            'num'                   => $productNum,
//            //  状态
//            'status'                => 'paying',
//            // 支付金额
//            'pay_amount'            => $totalAmount,
//            // 支付类型
////            'pay_type'              => null,
//        ];

        $order = $this->M->create($insertData);
        $data['union_order_sn'] = $order['order_sn'];

        return showSuccess($data);
    }

    //收益计算
    public function calcUserEarnings($userId, $productId, $productNum, $totalAmount){
        $modeProduct = ModeProduct::find($productId);
        //百分比 *100的
        $rate = $modeProduct['rate'];
        //本金 *100的
        $price = $modeProduct['price'];
        $add = [];
        $add['order_sn'] = 'MODE-A-' . date('YmdHis').strtoupper(Str::random());
        $add['user_id'] = $userId;
        $add['product_id'] = $productId;
        $add['num'] = $productNum;
        $add['pay_amount'] = $totalAmount;
        $add['principal'] = $totalAmount;
        $add['type'] = $modeProduct['type'];
        $add['earnings'] = $add['remain_earnings'] = (int)(($price * $rate) / 100) * $productNum;
        $add['achievements'] = '';
        $add['active_achievements'] = '';
        return $add;
    }

    public function information(){
        //整理数据
        $data = [
//            search: {enable: false, placeholder: '', button: ''},
//					types: {enable: false, lists: [{alias: '', name: ''}]},
//					popups: {services: {title: '', lists: [], tel: ''}}
            'main_title'=>'我的订购',
            'search'=>[
                'enable'=>true,
                'placeholder'=>'',
                'button'=>'搜索',
            ],
            'types'=>[
                'enable'=>false,
                'lists'=>[
                    [
                        'alias'=>'all',
                        'name'=>'全部',
                    ],
                    [
                        'alias'=>'mode_one',
                        'name'=>'产业订单一',
                    ],
                    [
                        'alias'=>'mode_two',
                        'name'=>'产业订单二',
                    ],
                    [
                        'alias'=>'mode_three',
                        'name'=>'产业订单三',
                    ]
                ]
            ],
            'popups'=>[
                'enable'=>true,
                'services'=>[
                    'title'=>'',
                    'params'=>[],
                    'tel'=>'',
                ]
            ],
        ];

        return showSuccess($data);
    }

    public function lists(){
        $params = request()->param();
        $currentPage = request()->param('page', 1);
        $start = ($currentPage - 1) * $this->pageSize;//1 0, 2 10, 3 20
        $type = request()->param('type', 'all');

        $userId = request()->UserModel->id;
        $map = [];
        switch ($type){
            case 'mode_one':
//                $map[] = ['type', 'between', [1, 2]];
                $map[] = ['type', '=', 1];
                break;
            case 'mode_two':
                $map[] = ['type', '=', 3];
                break;
            case 'mode_three':
                $map[] = ['type', '=', 4];
                break;
            default:
                $map[] = ['type', '>', 0];
                break;
        }
        $list = $this->M->with(['modeOrdersProduct'])
            ->where($map)
            ->where('user_id', $userId)
            ->where('status', 'payed')
            ->append(['status_format', 'count', 'params', 'goods_cover', 'release_status'])
            ->order('id DESC')
            ->limit($start, $this->pageSize)
//            ->fetchSql()
            ->select();
//        dd($list);
//            ->paginate($this->pageSize)
//            ->toArray();
        $data = [];
//        $data['total_page'] = (int)ceil($list['total']/$this->pageSize);;
        $data['page_size'] = $this->pageSize;
        $data['page'] = $currentPage;//$list['current_page'];
        $data['lists'] = $list;// $list['data'];

        return showSuccess($data);
    }
}